using ChikovMF.Application.Common.Exceptions;
using ChikovMF.Application.Common.Interfaces;
using ChikovMF.Application.Features.Files.Shared;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ChikovMF.Application.Features.Files.UpdateFile;

public class UpdateFileCommandHandler : IRequestHandler<UpdateFileCommand, FileDto>
{
    public async Task<FileDto> Handle(UpdateFileCommand request, CancellationToken cancellationToken)
    {
        var file = await _context.Files.FirstOrDefaultAsync(f => f.Name == request.FileName && f.PathLocation == request.PathLocation, cancellationToken);

        if (file == null)
        {
            throw new NotFoundEntityException(nameof(Entities.File), request.FileId);
        }

        var fileDto = await _fileManager.UpdateFile(request.FileStream, file.PathLocation, file.Name, cancellationToken);

        file.UploadDate = DateTime.UtcNow;

        await _context.SaveChangesAsync(cancellationToken);

        return fileDto;
    }

    private readonly IFileManager _fileManager;
    private readonly IChikovMFContext _context;
    public UpdateFileCommandHandler(IFileManager fileManager, IChikovMFContext context)
    {
        _fileManager = fileManager;
        _context = context;
    }
}